package com.hui.account.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.activity.RecordModActivity;
import com.hui.account.adapter.RecordAdapter;
import com.hui.account.database.SQLManage;
import com.hui.account.entity.RecordEntity;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.ButtonUtils;
import com.hui.account.utils.CommonUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 首页搜索
 */
public class SearchActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;

    Button eyeBtn, hideBtn;

    ListView recordList;

    EditText searchValue;

    ImageButton searchBack;

    RecordAdapter adapter;

    List<RecordEntity> data;

    SharedPreferences preferences; // preferences：共享参数，存储选中的欠款单信息

    TextView searchEmpty, searchTotalMoney, searchUserCount, searchRecordCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_search);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、初始化页面
        initView();

        // 3、preferences：共享参数初始化
        preferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);

        // 4、设置 ListView点击事件
        onClickRecordList();

        // 引入欠款记录适配器
        data = new ArrayList<>();
        adapter = new RecordAdapter(this, data);
        recordList.setAdapter(adapter);

        recordList.setEmptyView(searchEmpty);
    }

    private void initView() {
        eyeBtn = findViewById(R.id.main_search_eye);
        hideBtn = findViewById(R.id.main_search_hide);
        recordList = findViewById(R.id.main_search_records);
        searchValue = findViewById(R.id.main_search_value);
        searchBack = findViewById(R.id.main_search_back);
        searchEmpty = findViewById(R.id.main_search_empty);
        searchTotalMoney = findViewById(R.id.main_search_total_money);
        searchUserCount = findViewById(R.id.main_search_user_count);
        searchRecordCount = findViewById(R.id.main_search_record_count);

        eyeBtn.setOnClickListener(this);
        hideBtn.setOnClickListener(this);
        searchBack.setOnClickListener(this);
        searchValue.setOnClickListener(this);
    }

    /**
     * 欠款单适配器点击事件
     */
    private void onClickRecordList() {
        recordList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (!ButtonUtils.isFastDoubleClick()) {
                    // 1、获取到当前记录
                    RecordEntity record = data.get(i);

                    // 2、将数据存入共享参数
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putString("selectRecord", new Gson().toJson(record));
                    edit.commit();

                    startActivity(new Intent(context, RecordModActivity.class));
                }
            }
        });
    }

    /**
     * 清除 Tags
     */
    private void setSearchEmpty() {
        searchUserCount.setText("");
        searchTotalMoney.setText("");
        searchRecordCount.setText("");

        setGone();
    }

    /**
     * 隐藏 Tags
     */
    private void setGone() {
        searchUserCount.setVisibility(View.GONE);
        searchTotalMoney.setVisibility(View.GONE);
        searchRecordCount.setVisibility(View.GONE);
    }

    /**
     * 显示 Tags
     */
    private void setVisible() {
        searchUserCount.setVisibility(View.VISIBLE);
        searchTotalMoney.setVisibility(View.VISIBLE);
        searchRecordCount.setVisibility(View.VISIBLE);
    }

    /**
     * 搜索
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void searchClick() {
        // 搜索客户
        String value = searchValue.getText().toString().trim();
        if (!TextUtils.isEmpty(value)) {
            List<UserEntity> users = SQLManage.getUserByNameVague(value);
            if (users.size() > 0) {
                List<Integer> userIds = users.stream().map(UserEntity::getId).collect(Collectors.toList());
                List<RecordEntity> list = SQLManage.getUserRecords(userIds);
                if (list.size() > 0) {
                    List<Integer> collect = list.stream().map(RecordEntity::getUserId).distinct().collect(Collectors.toList());
                    searchUserCount.setText("总人数：" + collect.size() + " 人"); // 总人数
                    searchRecordCount.setText("欠款记录：" + list.size() + " 条"); // 欠款记录

                    // 计算总金额
                    BigDecimal totalMoney = new BigDecimal(0);
                    for (RecordEntity r : list) {
                        totalMoney = totalMoney.add(r.getMoney());
                    }
                    searchTotalMoney.setText("总金额：" + CommonUtils.MONEY + totalMoney);

                    data.clear();
                    data.addAll(list);
                } else {
                    setSearchEmpty();
                    data.clear();
                }
            } else {
                setSearchEmpty();
                data.clear();
            }
        } else {
            setSearchEmpty();
            data.clear();
        }
        adapter.notifyDataSetChanged();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_search_back:
                finish();
                break;
            case R.id.main_search_eye:
                if (!ButtonUtils.isFastDoubleClick()) {
                    if (!TextUtils.isEmpty(searchUserCount.getText().toString()) && !TextUtils.isEmpty(searchRecordCount.getText().toString()) && !TextUtils.isEmpty(searchTotalMoney.getText().toString())) {
                        eyeBtn.setVisibility(View.GONE);
                        hideBtn.setVisibility(View.VISIBLE);
                        setVisible();
                    }
                }
                break;
            case R.id.main_search_hide:
                if (!ButtonUtils.isFastDoubleClick()) {
                    if (!TextUtils.isEmpty(searchUserCount.getText().toString()) && !TextUtils.isEmpty(searchRecordCount.getText().toString()) && !TextUtils.isEmpty(searchTotalMoney.getText().toString())) {
                        hideBtn.setVisibility(View.GONE);
                        eyeBtn.setVisibility(View.VISIBLE);
                        setGone();
                    }
                }
                break;
            case R.id.main_search_value:
                if (!ButtonUtils.isFastDoubleClick())
                    searchClick();

                break;
        }
    }
}